import React, {useEffect, useState} from 'react';
import {Grid, Typography} from "@material-ui/core";
import DateFnsUtils from '@date-io/date-fns';
import {KeyboardDatePicker, MuiPickersUtilsProvider} from '@material-ui/pickers';
import {makeStyles} from "@material-ui/core/styles";
import {useDispatch} from "react-redux";
import {setTimeDuration} from "../../../../../../../redux/reducers/editor";

const useStyles = makeStyles((theme) => ({
  gutterBottom: {
    marginBottom: theme.spacing(2),
  },
  divider: {
    margin: theme.spacing(0, 1.5, 0, 1.5),
    color: theme.palette.grey[600]
  }
}));

export default function TimeFilter({timeDurationData}) {
  // Local constants
  const styles = useStyles();
  const dispatch = useDispatch();
  const today = new Date();
  const [endDate, setEndDate] = useState(timeDurationData.endDate);
  const [startDate, setStartDate] = useState(timeDurationData.startDate);

  useEffect(() => {
    return () => {
      dispatch(setTimeDuration(startDate, endDate))
    }
  }, [dispatch, startDate, endDate])

  // Function -> TimeFilter : sets the start date
  const handleStartDate = (date) => {
    setStartDate(date)
  }
  // Function -> TimeFilter : sets the end date
  const handleEndDate = (date) => {
    setEndDate(date)
  }

  return (
    <Grid container alignItems="center" className={styles.gutterBottom} xs={12}>
      <MuiPickersUtilsProvider utils={DateFnsUtils}>
        <Grid item xs>
          <KeyboardDatePicker
            fullWidth variant="dialog" inputVariant="outlined" format="dd/MM/yyyy"
            label={`Start Date`} value={startDate}
            onChange={handleStartDate} maxDate={endDate}
          />
        </Grid>
        <Typography variant="h6" className={styles.divider}>~</Typography>
        <Grid item xs>
          <KeyboardDatePicker
            fullWidth variant="dialog" inputVariant="outlined" format="dd/MM/yyyy"
            label={`End Date`} value={endDate}
            onChange={handleEndDate} minDate={startDate} maxDate={today}
          />
        </Grid>
      </MuiPickersUtilsProvider>
    </Grid>
  )
}
